//
//  FiveFromElevenViewController.m
//  DayAndDayLottery
//
//  Created by dengzhiping on 2017/5/27.
//  Copyright © 2017年 dengzhiping. All rights reserved.
//

#import "FiveFromElevenViewController.h"
#import "HomerHeader.h"

static NSString *numberCellIdentifier = @"SelectedNumberTableViewCellIdentifier";
static NSString *makeOrderSegueId = @"MakeOrderSegueId";

@interface FiveFromElevenViewController () <UIPageViewControllerDataSource,UIGestureRecognizerDelegate>{
    NSTimeInterval duringTimenIterval;
    NavigationItemTitleView *titleView;
}
@property (weak, nonatomic) IBOutlet UIView *lotteryTypeView;
@property (weak, nonatomic) IBOutlet UITableView *selectedTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectedTableViewConstraintTop;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIView *awardIntroduceVIew;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *arrowImv;
@property (weak, nonatomic) IBOutlet UILabel *qiHaoLabel;
@property (weak, nonatomic) IBOutlet UILabel *zjIntroduceLabel;
@property (weak, nonatomic) IBOutlet UILabel *xiaZhuLabel;
@property (nonatomic, strong) NSTimer *refreshTime;
@property (nonatomic, strong) HistoryLotteryViewController *historyVC;
@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, assign) NSInteger            time;
@property (nonatomic, strong) NSDictionary *dataDic;
@property (nonatomic, assign) NSInteger rowRount;
@property (nonatomic, strong) UIButton *tempBtn;
@property (nonatomic, strong) NSMutableArray *numberArray;
@property (nonatomic, assign) NSInteger chooseNum;

@end

@implementation FiveFromElevenViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUp];
    [self initData];

    WeakSelf
    self.selectedTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.historyVC initHistoryLotteryRequest];
        [Utils showToastMessage:@"期号已更新"];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    
    [self.refreshTime invalidate];
    self.refreshTime = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private Method
- (void)initData{
    _dataDic = [Utils readLocalDataWithFileName:@"LotyInfo" fileType:@"json"];
    NSDictionary *dic = [_dataDic objectForKey:@"data"];
    _qiHaoLabel.text = [NSString stringWithFormat:@"距%@期截止：",[dic objectForKey:@"qihao"]];
    
    NSString *endStr= [dic objectForKey:@"endselltime"];//时间戳
    NSString *curStr= [dic objectForKey:@"curtime"];//时间戳
    
    NSTimeInterval endTime=[endStr doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *endDate=[NSDate dateWithTimeIntervalSince1970:endTime];
    NSTimeInterval curTime=[curStr doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *curDate=[NSDate dateWithTimeIntervalSince1970:curTime];
    
    duringTimenIterval = [endDate timeIntervalSinceDate:curDate];
    self.time = duringTimenIterval;
    //self.time = 5;
    self.refreshTime = [NSTimer pltScheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshEndTime) userInfo:nil];
    self.numberArray = [NSMutableArray array];
}

- (void)refreshEndTime{
    
    if ([self.selectedTableView.mj_header isRefreshing]) {
        [self.selectedTableView.mj_header endRefreshing];
    }
    self.time = self.time - 1;
    
    NSString *str = [NSString stringWithFormat:@"%ld分%ld秒",self.time/60 ,self.time %60];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    if (str.length == 4) {
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:[UIColor redColor]
                        range:NSMakeRange(0, 1)];
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:[UIColor redColor]
                        range:NSMakeRange(2, 1)];
    }else{
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:[UIColor redColor]
                        range:NSMakeRange(0, 1)];
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:[UIColor redColor]
                        range:NSMakeRange(2, 2)];
    }

  
    self.timeLabel.attributedText = attrStr ;
    if (self.time <= 0) {
        
        self.time = duringTimenIterval;
        //self.time = 5;
        self.timeLabel.text = [NSString stringWithFormat:@"%ld分%ld秒",self.time/60 ,self.time %60];
        
        if (_selectedTableViewConstraintTop.constant == 220) {
            _selectedTableViewConstraintTop.constant = 0;
            [UIView animateWithDuration:0.25 animations:^{
                _arrowImv.transform = CGAffineTransformIdentity;
            }];
            [UIView animateWithDuration:0.15 animations:^{
                [self.view layoutIfNeeded];
            }];
        }
        
        [self.selectedTableView.mj_header beginRefreshing];
    }
 
}

- (void)setUp{
    self.rowRount = 1;
    self.chooseNum = 2;
    WeakSelf
    titleView = [NavigationItemTitleView initNavigationItemTitleViewFromXib];
    [titleView viewWithButtonTitle:@"任选二普通"];
    titleView.block = ^{
        if ([weakSelf.lotteryTypeView isHidden]) {
            [weakSelf.lotteryTypeView setHidden:NO];

        }else{
            [weakSelf.lotteryTypeView setHidden:YES];
        }
    };
    self.navigationItem.titleView = titleView;
    [self addCustumedBackButton];
    
    UIButton *helpItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [helpItemButton setImage:[UIImage imageNamed:@"icon_help"] forState:0];
    helpItemButton. frame = CGRectMake(0, 0, 30, 44);
    [helpItemButton addTarget:self action:@selector(helpButtonClicked) forControlEvents:UIControlEventTouchDown];
//    helpItemButton.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:helpItemButton];
    self.navigationItem.rightBarButtonItem = rightItem1;
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    singleRecognizer.numberOfTapsRequired = 1;
    [singleRecognizer setNumberOfTouchesRequired:1];
    [self.headerView addGestureRecognizer:singleRecognizer];
    
    self.pageViewController = self.childViewControllers.firstObject;
    self.historyVC = [HomeStory instantiateViewControllerWithIdentifier:@"HistoryLotteryViewControllerId"];
    self.pageViewController.dataSource = self;
    [self.pageViewController setViewControllers:@[self.historyVC]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:YES
                                     completion:nil];
    
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(notice:) name:@"buyCount" object:nil];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
    [self.selectedTableView addGestureRecognizer:panGesture];
    panGesture.delegate = self;
    panGesture.cancelsTouchesInView = NO;
    panGesture.delaysTouchesEnded = NO;
    
}
#pragma mark 处理拖拉
-(void)panView:(UIPanGestureRecognizer *)panGesture
{
    if (_selectedTableViewConstraintTop.constant == 220) {
        UIView *view = panGesture.view;
        if ( panGesture.state == UIGestureRecognizerStateChanged) {
            CGPoint translation = [panGesture translationInView:view.superview];
            panGesture.view.center = CGPointMake(panGesture.view.center.x , panGesture.view.center.y + translation.y);
            [panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
            if (translation.y < 0) {
                
                NSLog(@"%f",self.selectedTableView.y);
                if (self.selectedTableView.y > 280) {
                    _selectedTableViewConstraintTop.constant = 0;
                    [UIView animateWithDuration:0.5
                                          delay:0
                                        options:UIViewAnimationOptionCurveEaseOut
                                     animations:^{
                                         [self.view layoutIfNeeded];
                                         [self.selectedTableView.mj_header setHidden:NO];

                                     }
                                     completion:nil];
                    [UIView animateWithDuration:0.25 animations:^{
                        _arrowImv.transform = CGAffineTransformIdentity;
            
                    }];

                    
                    return;
                }
    
            }
        }
    }
}
#pragma mark - 手势代理
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer.view isKindOfClass:[UITableView class]]) {
        return YES;
    }
    return NO;
}

#pragma mark - 通知方法
-(void)notice:(NSNotification *)sender{
    NSDictionary *dic = sender.userInfo;
    NSArray *numArr = [dic objectForKey:@"buyCount"];
    [self.numberArray removeAllObjects];
    [self.numberArray addObjectsFromArray:numArr];

    if (self.numberArray.count == 0) {
        [self.awardIntroduceVIew setHidden:YES];
        self.xiaZhuLabel.text = [NSString stringWithFormat:@"0注0元"];
        
    }else{
        [self.awardIntroduceVIew setHidden:NO];
        self.xiaZhuLabel.text = [NSString stringWithFormat:@"%lu注%lu元",numArr.count,2 * numArr.count];
        self.zjIntroduceLabel.text = [NSString stringWithFormat:@"若中奖,奖金6 ~%lu元,盈利0 ~%lu元", 6 * numArr.count , 6 * numArr.count - 2 * numArr.count ];
    }
}



#pragma mark - Event Response
- (IBAction)makeOrderButton:(UIButton *)sender {
    
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempArray removeAllObjects];
    [tempArray addObjectsFromArray:self.numberArray];
    if (self.numberArray.count == 0) {
        [Utils showToastMessage:@"请选择号码"];
    }else{
    
        NSMutableString *numStr = [NSMutableString string];
        for (int i=0; i<tempArray.count; i++) {
        
            [numStr appendString:[NSString stringWithFormat:@"%@",tempArray[i]]];
            [numStr appendString:@" "];
        }
        [self performSegueWithIdentifier:makeOrderSegueId sender:numStr];
    }

}

- (IBAction)clearNumberButton:(UIButton *)sender {
    [self.awardIntroduceVIew setHidden:YES];
    self.xiaZhuLabel.text = [NSString stringWithFormat:@"0注0元"];
    self.chooseNum = 0;
    [self.numberArray removeAllObjects];
    [self.selectedTableView reloadData];
}

- (IBAction)tap:(UITapGestureRecognizer *)sender {
    if (![self.lotteryTypeView isHidden]) {
        [self.lotteryTypeView setHidden:YES];
    }
}
- (IBAction)lotteryTypeButton:(UIButton *)sender {
    

    if (self.tempBtn == nil) {
        sender.selected = !sender.selected;
        self.tempBtn = sender;
    }else{
        if (![sender isEqual:self.tempBtn]) {
            NSLog(@"不相同");
            self.tempBtn.selected = NO;
            sender.selected = !sender.selected;
            self.tempBtn = sender;

        }else{
            sender.selected = YES;
        }
    }
    
    
    WeakSelf
    if (![weakSelf.lotteryTypeView isHidden]) {
        [self.lotteryTypeView setHidden:YES];
    }
    
    if (_selectedTableViewConstraintTop.constant == 220) {
        _selectedTableViewConstraintTop.constant = 0;
        [UIView animateWithDuration:0.25 animations:^{
            _arrowImv.transform = CGAffineTransformIdentity;
        }];
        [UIView animateWithDuration:0.15 animations:^{
            [self.view layoutIfNeeded];
        }];
    }

    if ([sender.titleLabel.text hasSuffix:@"胆拖"]) {
        [titleView viewWithButtonTitle:[sender.titleLabel.text substringWithRange:NSMakeRange(0, sender.titleLabel.text.length )]];
        self.rowRount = 2;
        
    }else{
        [titleView viewWithButtonTitle:[sender.titleLabel.text substringWithRange:NSMakeRange(0, sender.titleLabel.text.length )]];
        self.rowRount = 1;
    }

    if ([sender.titleLabel.text hasPrefix:@"任选二"] || [sender.titleLabel.text hasPrefix:@"前二直选"]  || [sender.titleLabel.text hasPrefix:@"前二组选"]) {
        self.chooseNum = 2;
    }else if([sender.titleLabel.text hasPrefix:@"任选三"]|| [sender.titleLabel.text hasPrefix:@"前三直选"]  || [sender.titleLabel.text hasPrefix:@"前三组选"]){
        self.chooseNum = 3;
    }else if ([sender.titleLabel.text hasPrefix:@"任选四"]){
        self.chooseNum = 4;
    }else if ([sender.titleLabel.text hasPrefix:@"任选五"]){
        self.chooseNum = 5;
    }else if ([sender.titleLabel.text hasPrefix:@"任选六"]){
        self.chooseNum = 6;
    }else if ([sender.titleLabel.text hasPrefix:@"任选七"]){
        self.chooseNum = 7;
    }else if ([sender.titleLabel.text hasPrefix:@"任选八"]){
        self.chooseNum = 8;
    }else if ([sender.titleLabel.text hasPrefix:@"前一"]){
        self.chooseNum = 1;
    }
    
    [self.awardIntroduceVIew setHidden:YES];
    self.xiaZhuLabel.text = [NSString stringWithFormat:@"0注0元"];
    self.chooseNum = 0;
    [self.numberArray removeAllObjects];
    [self.selectedTableView reloadData];
    
}

- (void)singleTap:(UITapGestureRecognizer *)tapGestureRecognizer{
    if (_selectedTableViewConstraintTop.constant != 220) {
        _selectedTableViewConstraintTop.constant = 220;
        _arrowImv.transform = CGAffineTransformMakeRotation(M_PI);
        [UIView animateWithDuration:0.35 animations:^{
            [self.view layoutIfNeeded];
        }];
        [self.selectedTableView.mj_header setHidden:YES];
    }else{
        [self.selectedTableView.mj_header setHidden:NO];
        _selectedTableViewConstraintTop.constant = 0;
        [UIView animateWithDuration:0.25 animations:^{
            _arrowImv.transform = CGAffineTransformIdentity;
        }];
        [UIView animateWithDuration:0.35 animations:^{
            [self.view layoutIfNeeded];
        }];
    }
    
}


- (void)helpButtonClicked{
    NSLog(@"帮助说明");
    HelpViewController *help = [[HelpViewController alloc] init];
    help.url = @"https://github.com/dzp181/LearningSummary";
    [self.navigationController pushViewController:help animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.rowRount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SelectedNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:numberCellIdentifier];
    if (!cell) {
        cell = [[[NSBundle  mainBundle]  loadNibNamed:@"SelectedNumberTableViewCell" owner:self options:nil]  lastObject];
        
    }
    [cell randomNumerWithCount:self.chooseNum];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300;
}
#pragma mark - UIPageViewControllerDataSource
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    return nil;
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    return nil;
}


 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     if ([segue.identifier isEqualToString: makeOrderSegueId]) {
         MakeOrderViewController *makeOrder = segue.destinationViewController;
         makeOrder.selectedNums = sender;
     }
     
 }


@end
